//
//  MWFormulaController.m
//  XiRan-iOS
//
//  Created by liuyiming on 2019/11/18.
//  Copyright © 2019 Wood. All rights reserved.
//

#import "MWFormulaController.h"
#import <WebKit/WebKit.h>

@interface MWFormulaController () <WKUIDelegate, WKNavigationDelegate>

@property(nonatomic, strong) UIProgressView *progressView;
@property(nonatomic, strong) WKWebView *webView;

@end

@implementation MWFormulaController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = [[MWConfigManager manager] objectForKey:@"gongshibaojia" defaultValue:@"公式报价"];
    
    [self setupPageSubviews];
    [self loadFormulaConfig];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqual:@"estimatedProgress"] && object == self.webView) {
        [self.progressView setAlpha:1.0f];
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        if (self.webView.estimatedProgress  >= 1.0f) {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:YES];
            }];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView setNavigationDelegate:nil];
    [self.webView setUIDelegate:nil];
}

- (void)loadFormulaConfig {
    NSString *token = [MWUserManager manager].user.token;
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:token forKey:@"token"];
    [paraDic setObject:[MWConfigManager manager].productType forKey:@"is_material"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.label.text = [[MWConfigManager manager] objectForKey:@"loadin" defaultValue:@"加载中..."];
    
    MWWeakSelf
    [[MWNetworkManager manager] POST:kFormulaUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        self.webView.hidden = NO;
        self.errorTitleLabel.hidden = self.errorImageView.hidden = YES;
        if (code == 1) {
            [hud hideAnimated:YES];
            NSString *url = [NSString stringWithFormat:@"https://%@", [dic objectForKey:@"data"]];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
            [weakSelf.webView loadRequest:request];
        } else {
            hud.mode = MBProgressHUDModeText;
            hud.label.text = msg;
            [hud hideAnimated:YES afterDelay:2];
        }
        
    } failure:^(NSError *error) {
        [hud hideAnimated:YES];
        if ([MWConfigManager manager].isNetError) {
            self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"click_retry" defaultValue:@"点击重试"];
            self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
            self.webView.hidden = YES;
        }

    }];
}

- (void)refresh {
    [super refresh];
    [self loadFormulaConfig];
}


- (void)setupPageSubviews {
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    WKPreferences *preference = [[WKPreferences alloc]init];
    preference.javaScriptEnabled = YES;
    preference.javaScriptCanOpenWindowsAutomatically = YES;
    config.preferences = preference;
    
    _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    _webView.allowsBackForwardNavigationGestures = YES;
    [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
    [self.view addSubview:self.webView];
    
    _progressView = [[UIProgressView alloc] init];
    _progressView.progressTintColor = [UIColor greenColor];
    [self.view addSubview:_progressView];
    
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.equalTo(@2);
    }];
}


@end
